import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { Alert, Input, Modal } from 'antd'
import createStore, { Connect, IPreact } from 'ipreact-for-react'
import { ModalProps } from 'antd/lib/modal'

const store: IPreact<PromptProps> = createStore()({ visible: false })

const _Prompt = (props: PromptProps) => {
    const { placeholder, value, onResult, invalid_message, ...others } = props
    const [v, setValue] = React.useState(value)
    const inputRef = React.createRef<Input>()

    React.useEffect(function () {
        setValue(value)
        if (inputRef.current) {
            inputRef.current.setValue(value)
        }
    }, [value, props.visible])
    const on_result = (value: string) => {
        onResult(value)
        store.dispatch(state => ({ ...state, visible: false }))
    }

    const error = invalid_message ? invalid_message(v) : null
    return <Modal {...others} onOk={() => on_result(v)} okButtonProps={{ disabled: !!error }} onCancel={() => on_result(null)}>
        <Input.Password placeholder={placeholder} ref={inputRef} onChange={e => setValue(e.target.value)}/>
        <div>&nbsp;</div>
        {error && <Alert message={error} type="error" showIcon />}
    </Modal>
}


interface PromptProps extends ModalProps {
    value?: string
    placeholder?: string
    invalid_message?: (v: string) => string
    onResult?: (value: string) => void
}

export const prompt = (props: PromptProps) => new Promise<string>(resolve => store.dispatch((state) => {
    return {
        ...state,
        visible: true,
        ...props,
        onResult: resolve,
    }
}))

const connect: Connect<PromptProps> = store.connect
const Prompt = connect(() => {
    return store.getState()
})(_Prompt)

const div = document.createElement('div')
document.body.appendChild(div)
ReactDOM.render(<Prompt />, div)
